#include "head.h"
#define MAX 1000
int main(int argc,char *argv[]){
    //./server 172.22.123.229 1234 4
    ARGS_CHECK(argc,4);
    int workerNum = atoi(argv[3]);
    threadPool_t threadPool;
    threadPoolInit(&threadPool,workerNum);
    int sockFd;
    makeWorker(&threadPool);
    tcpInit(argv[1],argv[2],&sockFd);
    task_t *pTask = (task_t *)calloc(1,sizeof(task_t));
    strcpy(pTask->salt,"$6$uw4F3Kne$");//神秘固定盐值

    //开始epoll监听
    int epfd = epoll_create(10);
    epollAdd(sockFd,epfd);
    struct epoll_event readyList[100];//就绪的数组
    
    int clientFd[MAX]={0};//监听数组写大一点~
    int fdNum=0;//监听数组下标
    while (1)
    {
        int readyNum = epoll_wait(epfd,readyList,100,-1);
        puts("epoll ready");
        for(int i =0;i<readyNum;i++){
            if(readyList[i].data.fd == sockFd){
                int netFd = accept(sockFd,NULL,NULL);
                //接收token，如果是第一次connect token为0
                printf("netFd=%d\n",netFd);
                recv(netFd,pTask->token,98,0);
                printf("token = %s\n",pTask->token);
                if(strlen(pTask->token)!=0){
                    //事件队列是共享资源，需要加锁保护
                    pthread_mutex_lock(&threadPool.mutex);
                    enQueue(&threadPool.taskQueue,netFd);
                    puts("new Task");
                    pthread_cond_signal(&threadPool.cond);
                    pthread_mutex_unlock(&threadPool.mutex);
                }else{
                    while(clientFd[fdNum]!=0){//直到这个位置无人占用
                        fdNum++;
                        if(fdNum==MAX){
                            fdNum=0;//循环数组
                        }
                    }
                    clientFd[fdNum]=netFd;
                    epollAdd(clientFd[fdNum],epfd);
                    //登录时用户名与固定盐值制作一个token
                    char token[100]={0};
                    strcpy(token,crypt("chao",pTask->salt));
                    puts("-----first login-----");
                    //发给客户端token
                    send(netFd,token,98,0);
                    //printf("fdNum = %d,clientFd[fdNum] = %d\n",fdNum,clientFd[fdNum]);
                    fdNum++;
                }
            }
            for(int j=0;j<fdNum;++j){
                if(readyList[i].data.fd == clientFd[j]){
                    puts("欢迎来到短命令");
                    task_t mypTask = *pTask; //接收下来
                    mypTask.netFd=clientFd[j];
                    bzero(mypTask.buf,sizeof(mypTask.buf));
                    int ret = recv(mypTask.netFd,mypTask.buf,sizeof(mypTask.buf),0);
                    if(ret == 0){
                        epollDel(clientFd[j],epfd);
                        clientFd[j]=0;
                        puts("对面客户端断开！");
                        break;
                    }
                    sOrderJudge(&mypTask);
                }
            }
        }
    }
}